﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;   

namespace FrontEndPlus
{
    public class IPSegment
    {
        private UInt32 _ip;
        private UInt32 _mask;

        public UInt32 NumberOfHosts
        {
            get { return ~_mask + 1; }
        }

        public UInt32 NetworkAddress
        {
            get { return _ip & _mask; }
        }

        public UInt32 BroadcastAddress
        {
            get { return NetworkAddress + ~_mask; }
        }

        public IPSegment(string IP, string mask)
        {
            _ip = IP.ParseIP();
            _mask = mask.ParseIP();
        }

        public IEnumerable<UInt32> Hosts()
        {
            for (var host = NetworkAddress + 1; host < BroadcastAddress; host++)
            {
                yield return host;
            }
        }

    }

    public static class IPHelpers
    {
        public static string ToIPString(this UInt32 value)
        {
            var bitmask = 0xff000000;
            var parts = new string[4];

            for (var i = 0; i < 4; i++)
            {
                var masked = (value & bitmask) >> ((3 - i) * 8);
                bitmask >>= 8;
                parts[i] = masked.ToString(CultureInfo.InvariantCulture);
            }

            return String.Join(".", parts);
        }

        public static UInt32 ParseIP(this string IPAddress)
        {
            var splitted = IPAddress.Split('.');
            UInt32 IP = 0;

            for (var i = 0; i < 4; i++)
            {
                IP = (IP << 8) + UInt32.Parse(splitted[i]);
            }

            return IP;
        }
    }
}